import { SQLiteFS } from 'absurd-sql'
import initSqlJs from 'sql.js'

// 1. 初始化IndexedDB文件系统
function createFileSystem() {
  return new Promise((resolve) => {
    const request = indexedDB.open('SQLiteStorage', 1)

    request.onupgradeneeded = (e) => {
      const db = e.target.result
      if (!db.objectStoreNames.contains('files')) {
        db.createObjectStore('files')
      }
    }

    request.onsuccess = (e) => {
      const db = e.target.result
      const transaction = db.transaction('files', 'readwrite')
      const store = transaction.objectStore('files')
      resolve(store)
    }
  })
}

// 2. 初始化SQLite数据库
async function initSQLiteDB() {
  const [SQL, store] = await Promise.all([
    initSqlJs({ locateFile: file => `/node_modules/sql.js/dist/${file}` }),
    createFileSystem()
  ]);

  const fs = new SQLiteFS({
    store: {
      put: (key, data) => store.put(data, key),
      get: (key) => store.get(key),
      del: (key) => store.delete(key),
      keys: () => {
        return new Promise(resolve => {
          const keys = []
          store.openCursor().onsuccess = (e) => {
            const cursor = e.target.result
            if (cursor) {
              keys.push(cursor.key)
              cursor.continue()
            } else {
              resolve(keys)
            }
          }
        })
      }
    }
  });

  try {
    const db = new SQL.Database('/telemetry.db', { fileSystem: fs });
    db.exec(`
      CREATE TABLE IF NOT EXISTS telemetry (
        id INTEGER PRIMARY KEY,
        timestamp INTEGER NOT NULL,
        dateTime TEXT NOT NULL,
        parsedData TEXT NOT NULL,
        sourceCode TEXT
      );
    `);
    return db;
  } catch (error) {
    console.error('Database initialization failed:', error);
    throw new Error('Unable to initialize database');
  }
}


// 3. 从IndexedDB读取原始数据
function readSourceData() {
  return new Promise((resolve, reject) => {
    const request = indexedDB.open('TelemetryDB')

    request.onsuccess = (e) => {
      const db = e.target.result
      const tx = db.transaction('telemetry', 'readonly')
      const store = tx.objectStore('telemetry')
      const data = []

      store.openCursor().onsuccess = (event) => {
        const cursor = event.target.result
        if (cursor) {
          data.push(cursor.value)
          cursor.continue()
        } else {
          resolve(data)
        }
      }
    }

    request.onerror = reject
  })
}

// 4. 执行迁移
export async function migrate() {
  let targetDB;
  try {
    const [sourceData, db] = await Promise.all([
      readSourceData(),
      initSQLiteDB()
    ]);

    targetDB = db;

    const BATCH_SIZE = 1000;
    targetDB.exec('BEGIN TRANSACTION');

    const stmt = targetDB.prepare(`
      INSERT INTO telemetry
      (id, timestamp, dateTime, parsedData, sourceCode)
      VALUES (?, ?, ?, ?, ?)
    `);

    for (let i = 0; i < sourceData.length; i++) {
      const item = sourceData[i];
      stmt.bind([
        item.id,
        item.timestamp,
        new Date(item.dateTime).toISOString(),
        JSON.stringify(item.parsedData),
        item.sourceCode || null
      ]);
      stmt.step();
      stmt.reset();

      if (i % BATCH_SIZE === 0) {
        targetDB.exec('COMMIT');
        targetDB.exec('BEGIN TRANSACTION');
      }
    }

    targetDB.exec('COMMIT');
    stmt.free();
    console.log(`成功迁移 ${sourceData.length} 条记录`);
  } catch (error) {
    console.error('迁移失败:', error);
    if (targetDB) targetDB.exec('ROLLBACK');
  } finally {
    if (targetDB) targetDB.close();
  }
}
